import requests
from src.config import API_KEY, SECRET_KEY
ACCESS_TOKEN_URL = 'https://aip.baidubce.com/oauth/2.0/token'
TTS_URL = 'https://tsn.baidu.com/text2audio'

def get_access_token():
    url = 'https://aip.baidubce.com/oauth/2.0/token'
    params = {
        'grant_type': 'client_credentials',
        'client_id': API_KEY,
        'client_secret': SECRET_KEY
    }
    response = requests.post(url, params)
    response.raise_for_status()  # 如果请求失败，抛出异常
    return response.json().get('access_token')

def text_to_speech(text):
    print("Converting text to speech...")
    access_token = get_access_token()
    if not access_token:
        raise Exception("Failed to retrieve access token.")
    
    # 定义请求参数
    params = {
        'tex': text,
        'tok': access_token,
        'cuid': 'your_unique_cuid',
        'ctp': 1,
        'lan': 'zh',
        'per': 4
    }

    # print('params:', params)
    
    # 使用data参数发送表单数据
    response = requests.post(TTS_URL, data=params, stream=True)
    
    if response.headers.get('Content-Type') == 'audio/mp3':
        return response.content
    else:
        # 如果响应不是MP3，处理错误
        # print(response.json())
        error_msg = response.json().get('error_msg', 'Unknown error')
        raise Exception(f"Failed to convert text to speech: {error_msg}")
    
if __name__ == "__main__":
    # 测试代码
    response_audio = text_to_speech("测试文本,测试文本,测试文本,测试文本,测试文本")
    with open('output.mp3', 'wb') as f:
        f.write(response_audio)
